import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.inspection import permutation_importance
from sklearn.svm import SVR
from sklearn.preprocessing import MinMaxScaler
from scipy.stats import pearsonr
import matplotlib.pyplot as plt

import matplotlib

matplotlib.use('TkAgg')

import matplotlib as mpl

# 配置中文显示
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False


def concordance_correlation_coefficient(y_true, y_pred):
    mean_true = np.mean(y_true)
    mean_pred = np.mean(y_pred)
    var_true = np.var(y_true)
    var_pred = np.var(y_pred)
    covar = np.cov(y_true, y_pred)[0, 1]
    return (2 * covar) / (var_true + var_pred + (mean_true - mean_pred) ** 2)


def svm_analysis(data_path, n_repeats=20):
    # 数据加载与预处理
    data = pd.read_excel(data_path)
    X = data.drop('SD', axis=1).values
    y = data['SD'].values
    feature_names = data.drop('SD', axis=1).columns

    scaler = MinMaxScaler()
    X = scaler.fit_transform(X)

    # 结果存储
    metrics = []
    all_importances = []

    for _ in range(n_repeats):
        # 数据划分
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

        # 训练SVM模型
        model = SVR(kernel='rbf', C=1.0, epsilon=0.1)
        model.fit(X_train, y_train)

        # 预测与评估
        y_pred = model.predict(X_test)
        metrics.append([
            pearsonr(y_test, y_pred)[0] ** 2,
            concordance_correlation_coefficient(y_test, y_pred),
            np.sqrt(np.mean((y_test - y_pred) ** 2)),
            np.mean(np.abs(y_test - y_pred))
        ])

        # 计算排列重要性
        result = permutation_importance(model, X_test, y_test, n_repeats=20, random_state=42)
        all_importances.append(result.importances_mean)

    # 处理结果
    metrics_df = pd.DataFrame(metrics, columns=['R2', 'CCC', 'RMSE', 'MAE'])
    importance_df = pd.DataFrame(np.mean(all_importances, axis=0), index=feature_names, columns=['Importance'])

    # 可视化特征重要性
    plt.figure(figsize=(12, 6))
    sorted_importance = importance_df.sort_values(by='Importance', ascending=False)
    plt.bar(range(len(sorted_importance)), sorted_importance['Importance'])
    plt.xticks(range(len(sorted_importance)), sorted_importance.index, rotation=45)
    plt.xlabel('特征名称')
    plt.ylabel('排列重要性')
    plt.title('SVM特征重要性分析')
    plt.tight_layout()
    plt.savefig('svm_feature_importance.png', dpi=300)
    plt.show()

    # 保存结果
    metrics_df.to_excel('svm_metrics.xlsx', index=False)
    sorted_importance.to_excel('svm_feature_importance.xlsx')

    return metrics_df, sorted_importance


# 使用
metrics, importance = svm_analysis(r'C:\Users\32407\Desktop\soil-terrain attributes.xlsx', n_repeats=20)
print("平均性能指标:\n", metrics.mean())
print("\n特征重要性排序:\n", importance)
